package com.authine.cloudpivot.ext.kingdee.jdbc;

import com.alibaba.cola.dto.RequestContext;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.KingDeeConstant;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.voucher.KingDeeBasicStats;
import com.authine.cloudpivot.ext.enums.kingdee.KingDeeBasicStatsEnum;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;


import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liwei
 * @DateTime: 2021/7/20
 * @Description: TODO
 */
@Slf4j
public class KingDeeBasicStatsRepository {


    /**
     * 新建金蝶基础数据
     *
     * @param data
     * @return
     */
    public String create(Map<String, Object> data) {

        BoResultFormat.initSys(RequestContext.getCorpLoginId(), data);
        //重新写入一条新的数据
        int insert = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS).putFieldAndVal(data).insert();
        Assert.isTrue(insert > 0, "KingDeeBasicStatsRepository create 保存失败！！！");
        return data.get("id").toString();
    }

    /**
     * 根据公司名称，找到对应金蝶数据
     *
     * @param names 名称集合
     * @return
     */
    public List<KingDeeBasicStats> findByCompanyNames(List<String> names) {

        List<Map<String, Object>> result = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .selectField(" * ")
                .in(KingDeeConstant.COMPANY_NAME_FIELD, names).queryForList();
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }

        List<KingDeeBasicStats> kingDeeBasicStatsList = JsonParseObject.parseObject(JSON.toJSONString(result), KingDeeBasicStats.class);
        return kingDeeBasicStatsList;
    }

    public List<KingDeeBasicStats> findByCompanyNameLike(String companyName) {

        List<Map<String, Object>> result = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .selectField(" * ")
                .like(KingDeeConstant.COMPANY_NAME_FIELD, companyName).queryForList();

        if (CollectionUtils.isEmpty(result)) {
            return null;
        }

        List<KingDeeBasicStats> kingDeeBasicStatsList = JsonParseObject.parseObject(JSON.toJSONString(result), KingDeeBasicStats.class);
        return kingDeeBasicStatsList;
    }

    public List<String> createBatch(List<KingDeeBasicStats> kingDeeBasicStatsList) {
        Map<String, Object>[] param = new Map[kingDeeBasicStatsList.size()];

        for (int i = 0; i < kingDeeBasicStatsList.size(); i++) {

            Assert.isTrue(StringUtils.isNotBlank(kingDeeBasicStatsList.get(i).getCompany_name()), "金蝶基础数据名称字段不能为空");
            Assert.isTrue(StringUtils.isNotBlank(kingDeeBasicStatsList.get(i).getKingdee_code()), "金蝶基础数据编码字段不能为空");


            Map<String, Object> data = JSON.parseObject(JSON.toJSONString(kingDeeBasicStatsList.get(i)), HashMap.class);
            BoResultFormat.initSys(RequestContext.getCorpLoginId(), data);
            param[i] = data;
        }

        int[] result = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS).putFieldAndValList(param).insertBatch();
        log.info("批量保存结果 result:{}", result);

        Arrays.stream(result).forEach(e -> Assert.isTrue(e > 0, "创建金蝶基础数据 失败"));

        List<String> ids = new ArrayList();
        for (Map<String, Object> map : param) {
            ids.add(String.valueOf(map.get("id")));
        }
        return ids;
    }

    public KingDeeBasicStats findById(String id) {

        Map<String, Object> result = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .selectField(" * ")
                .eq(KingDeeConstant.ID_FIELD, id)
                .queryForMap();

        if (null == result) {
            return null;
        }

        KingDeeBasicStats kingDeeBasicStats = JSON.parseObject(JSON.toJSONString(result), KingDeeBasicStats.class);
        return kingDeeBasicStats;
    }

    public int updateCompanyAndKingdee(KingDeeBasicStats kingDeeBasicStats) {

        Map<String, Object> data = new HashMap<>();

        if (StringUtils.isNotBlank(kingDeeBasicStats.getCompany_name())) {
            data.put(KingDeeConstant.COMPANY_NAME_FIELD, kingDeeBasicStats.getCompany_name());

        }

        if (StringUtils.isNotBlank(kingDeeBasicStats.getKingdee_code())) {
            data.put(KingDeeConstant.KINGDEE_CODE_FIELD, kingDeeBasicStats.getKingdee_code());

        }

        if (null != kingDeeBasicStats.getInfo_type()) {
            data.put(KingDeeConstant.INFO_TYPE_FIELD, kingDeeBasicStats.getInfo_type().getName());

        }

        int update = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .putFieldAndVal(data)
                .in(KingDeeConstant.ID_FIELD, kingDeeBasicStats.getId())
                .update();
        return update;
    }

    /**
     * 判断code
     *
     * @param code
     * @param companyName
     * @return
     */
    public Boolean checkCodeAndNameExist(String code, String companyName, KingDeeBasicStatsEnum type) {

        List<Map<String, Object>> codeList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .selectField("*").eq(KingDeeConstant.KINGDEE_CODE_FIELD, code).eq(KingDeeConstant.INFO_TYPE_FIELD, type.getName()).queryForList();
        if (!CollectionUtils.isEmpty(codeList)) {
            return true;
        }
        List<Map<String, Object>> companyNameList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS)
                .selectField("*").eq(KingDeeConstant.COMPANY_NAME_FIELD, companyName).eq(KingDeeConstant.INFO_TYPE_FIELD, type.getName()).queryForList();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            return true;
        }
        List<Map<String, Object>> mapList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_KINGDEE_BASIC_STATS).selectField("*")
                .eq(KingDeeConstant.KINGDEE_CODE_FIELD, code).eq(KingDeeConstant.COMPANY_NAME_FIELD, companyName).eq(KingDeeConstant.INFO_TYPE_FIELD, type.getName()).queryForList();
        if (!CollectionUtils.isEmpty(mapList)) {
            return true;
        }
        return false;
    }
}
